<template>
  <base-modal
    :title="title"
    width="480px"
    @cancel="cancel"
    :show.sync="isShow"
    :mask-closeable="false">
    <div v-if="!clickTaskType" class="add-task-type">
      <el-row type="flex" justify="space-between">
        <el-card
          class="choose-type-box"
          :style="{'background-image': 'url(' + item.bgImg + ')'}"
          v-for="item in taskTemplateList"
          :key="item.type"
          shadow="hover"
          @click.native="chooseTypeTemplate(item.type)"
        >
          <div class="choose-type-box-content">
            <h2>{{item.title}}</h2>
            <p class="task-type-desc">{{item.desc}}</p>
          </div>
        </el-card>
      </el-row>
    </div>
    <el-form label-position="top" v-else :model="form" :rules="rules" @submit.native.prevent ref="form" class="add-task-form">
      <el-form-item v-if="clickTaskType === 'exist'" :label="$t('product.setting.qrCodeSet.createTemplate.label1')" prop="templateId">
        <el-select v-model="form.templateId" :placeholder="$t('product.setting.qrCodeSet.createTemplate.pla1')" class="w-300">
          <el-option
            v-for="item in templateList"
            :key="item.id"
            :label="item.productIntroduction"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('product.setting.qrCodeSet.createTemplate.label2')" prop="productIntroduction">
        <el-input class="w-300" @keyup.enter.native.prevent="createTemplate" v-model="form.productIntroduction" :placeholder="$t('product.setting.qrCodeSet.createTemplate.pla2')"></el-input>
      </el-form-item>
    </el-form>

    <div v-if="clickTaskType" slot="footer">
      <el-button @click="cancel">{{$t('common.base.cancel')}}</el-button>
      <el-button :loading="pedding" type="primary" @click="createTemplate">{{$t('common.base.confirm')}}</el-button>
    </div>

  </base-modal>
</template>

<script>
import { getOssUrl } from '@src/util/assets'
// assets
const taskTemplateBlank = getOssUrl('/setting/task-template-blank.png');
const taskTemplateCopy = getOssUrl('/setting/task-template-copy.png');
import {
  saveSuperCodeTemplate,
  copyTemplate
} from '@src/api/SuperQrcode';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'
export default {
  name:'create-template',
  props: {
    visiable: {
      type: Boolean,
      default: false
    },
    templateList: {
      type: Array,
      default: () => []
    },
    tenantId:{
      type:String,
      default:''
    },
    lastForm:{
      type:Object,
      default:()=>{}
    }
  },
  data() {
    let validateTypeName = (rule, value, callback) => {
      if (value === '') return callback(new Error(i18n.t('product.setting.qrCodeSet.createTemplate.tips1')));
      if(value.length > 100) callback(new Error(i18n.t('common.validate.nameLimit',{limit: 100})));
      // if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) return callback(new Error(i18n.t('product.setting.qrCodeSet.createTemplate.tips3')));

      callback();
    };

    return {
      clickTaskType: '',

      form: {
        productIntroduction: '',
        templateId: '',
      },
      rules: {
        templateId: [{ required: true, message: i18n.t('product.setting.qrCodeSet.createTemplate.tips4'), trigger: 'blur' }],
        productIntroduction: [
          { required: true, message: i18n.t('product.setting.qrCodeSet.createTemplate.tips1'), trigger: 'blur' },
          { validator: validateTypeName, trigger: 'blur' }
        ]
      },
            
      pedding: false,
      isShow: false,
      isShowChooseTradeDialog: false,
    }
  },
  computed: {
    title() {
      return this.clickTaskType 
        ? this.taskTemplateList.find(item => item.type === this.clickTaskType).title
        : this.$t('product.setting.qrCodeSet.createTemplate.title1');
    },
    taskTemplateList() {
      return [
        {
          type: 'blank',
          title: this.$t('product.setting.qrCodeSet.createTemplate.title2'),
          desc: this.$t('product.setting.qrCodeSet.createTemplate.des1'),
          bgImg: taskTemplateBlank
        },
        {
          type: 'exist',
          title: this.$t('product.setting.qrCodeSet.createTemplate.title3'),
          desc: this.$t('product.setting.qrCodeSet.createTemplate.des2'),
          bgImg: taskTemplateCopy
        }
      ]
    }
  },
  watch: {
    visiable(newVal){
      this.isShow = newVal;
    }
  },
  methods: {
    cancel() {
      let _this = this;
      this.$emit('update:visiable', false);
      setTimeout(() => {
        Object.assign(this.$data, this.$options.data());
        _this.$refs.form.resetFields();
      }, 100)
    },
    /** 选择新建类型 */
    chooseTypeTemplate(type) {
      if(type === 'template') {
        return this.isShowChooseTradeDialog = true;
      }

      this.clickTaskType = type;
    },
    // 新建/复制模版
    createTemplate(){
      this.$refs.form.validate(valid => {
        if(valid){
          let params=null;
          if(this.clickTaskType==='blank'){
            params={
              tenantId:this.tenantId,
              productIntroduction:this.form.productIntroduction
            }
          }else{
            params={
              tenantId:this.tenantId,
              productIntroduction:this.form.productIntroduction,
              templateId:this.form.templateId
            }
          }
          this.saveTemplate(this.clickTaskType,params);
        }
      })
    },
    async saveTemplate(type,params){
      try{
        let fn=type==='blank'?saveSuperCodeTemplate:copyTemplate;
        let {code,data,msg}=await fn(params);
        if(code==='200'){
          const param={
            id:data.templateId,
            doorEventType:data.doorEventType || [],
            showFields:data.showFields || [],
            setting:data.setting || {},
            catalogId:1,
            productIntroduction:data.productIntroduction,
            lastForm:this.lastForm
          }
          window.sessionStorage.setItem('edit_qrcode_template_params',JSON.stringify(param));
          // this.$platform.openTab({
          //   id: 'superqrcodeSet',
          //   title: '产品二维码配置',
          //   close: true,
          //   url: '/setting/superQrcode',
          //   reload:true
          // });
          openAccurateTab({
            type: PageRoutesTypeEnum.PageSettingSuperQrcode,
            reload:true,
          })
          let id = window.frameElement && window.frameElement.dataset.id;
          this.$platform.closeTab(id);
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: msg
          })
        }
      }catch(err){
        console.error(err);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.add-task-type{
    max-height: 403px;
    padding: 40px 40px 20px 40px;
    overflow: hidden;
    .choose-type-box{
        cursor: pointer;
        position: relative;
        width: 183px;
        height: 244px;
        border-radius: 10px;

        background-repeat: no-repeat;
        background-position: center center;
        background-size: cover;

        &.active{
            .choose-type-box-content{
                transform: translateY(0);
                p{
                    opacity: 1;
                }
            }
        }

        .choose-type-box-content{
            position: absolute;
            left: 16px;
            bottom: 17px;
            color: #FFFFFF;
            transform: translateY(22px);
            transition: all .5s ease;

            h2{
                margin-bottom: 5px;
                font-size: 16px;
            }
            p{
                margin-bottom: 0;
                font-size: 12px;
                opacity: 0;
                transition: all .5s ease;
            }

        }
    }
}

.add-task-form{
    padding: 20px;
    ul.statecolor{
        padding: 0;
        line-height: 22px;
        li{
            list-style: none;
            display: inline-block;
            cursor: pointer;
            margin-right: 4px;
            width: 32px;
            height: 22px;
            vertical-align: middle;
            i{
                position: relative;
                font-weight: bold;
                left: 9px;
                color: #fff;
            }
        }
    }
}

.w-360{
    width: 360px;
}
.w-300{
  width:300px;
}
</style>